from fastapi import APIRouter, Depends, HTTPException, status, UploadFile
from app.schemas import schemas
from sqlalchemy.orm import Session
from app.db.db import get_db
from app.models import models
from app.dependencies import (
    get_current_user,
    get_current_active_user,
    get_current_active_admin,
)
from app.db import crud
from typing import List
from app.services.icon_file_service import FileService

router = APIRouter(tags=["icons"])


@router.get("/icons", response_model=List[schemas.IconFile])
async def get_icon_files(
    db: Session = Depends(get_db),
    current_user: schemas.User = Depends(get_current_active_user),
):
    icon_files = crud.get_icon_files(db)
    return icon_files


# 上传图标文件
@router.post("/icons/upload", response_model=schemas.IconFile)
async def upload_icon(
    file: UploadFile,
    current_user: models.DUser = Depends(get_current_active_admin),
    db: Session = Depends(get_db),
):
    try:
        icon_file = await FileService.save_icon(file, current_user.id)
        db_icon_file = crud.create_icon_file(db, schemas.IconFileCreate(**icon_file), current_user.id)
        print(f"Icon file uploaded: {db_icon_file.file_name}, URL: {db_icon_file.file_url}")
        return db_icon_file
    except HTTPException as e:
        raise HTTPException(
            status_code=e.status_code, detail=f"File upload failed: {e.detail}"
        )


# 删除图标文件
@router.delete("/icons/{icon_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_icon_file(
    icon_id: int,
    current_user: models.DUser = Depends(get_current_active_admin),
    db: Session = Depends(get_db),
):
    try:
        dicon = crud.get_icon_file(db, icon_id)
        if dicon is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="Icon file not found"
            )
        
        crud.delete_icon_file(db, icon_id)
        
        # 删除文件
        result = await FileService.delete_icon(dicon.file_url)
        
        if not result:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="Icon file not found"
            )
    except HTTPException as e:
        raise HTTPException(
            status_code=e.status_code, detail=f"File deletion failed: {e.detail}"
        )
    return


@router.put("/icons/{icon_id}", response_model=schemas.IconFile)
async def update_icon_file(
    icon_id: int,
    file: UploadFile,
    db: Session = Depends(get_db),
    current_user: models.DUser = Depends(get_current_active_user),
):
    db_icon_file = crud.get_icon_file(db, icon_id)

    if db_icon_file is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Icon file not found"
        )

    try:
        # 删除旧文件
        await FileService.delete_icon(db_icon_file.file_url)
        
        icon_file = await FileService.save_icon(file, current_user.id)
        updated_icon_file = schemas.IconFileUpdate(**icon_file)
        
        return crud.update_icon_file(db, icon_id, updated_icon_file)
    except HTTPException as e:
        raise HTTPException(
            status_code=e.status_code, detail=f"File upload failed: {e.detail}"
        )
    


# @router.delete("/icon_files/{icon_file_id}", status_code=status.HTTP_204_NO_CONTENT)
# async def delete_icon_file(
#     icon_file_id: int,
#     db: Session = Depends(get_db),
#     current_user: models.DUser = Depends(get_current_active_user),
# ):
#     result = crud.delete_icon_file(db, icon_file_id, current_user.id)

#     if not result:
#         raise HTTPException(
#             status_code=status.HTTP_404_NOT_FOUND, detail="Icon file not found"
#         )
#     return {"detail": "Icon file deleted successfully"}


# @router.get("/icons", response_model=schemas.IconFile)
# async def get_icon_file(
#     icon_file_id: int,
#     db: Session = Depends(get_db),
#     current_user: models.DUser = Depends(get_current_active_user),
# ):
#     db_icon_file = crud.get_icon_file(db, icon_file_id, current_user.id)

#     if db_icon_file is None:
#         raise HTTPException(
#             status_code=status.HTTP_404_NOT_FOUND, detail="Icon file not found"
#         )

#     return db_icon_file
